package com.sunday.authorization.mock.oauth2.server.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.oauth2.server.authorization.config.annotation.web.configurers.OAuth2AuthorizationServerConfigurer;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
import org.springframework.security.web.util.matcher.MediaTypeRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;


@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    @Order(1)
    public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http)
            throws Exception {

        OAuth2AuthorizationServerConfigurer authorizationServerConfigurer =
                new OAuth2AuthorizationServerConfigurer();
        authorizationServerConfigurer
                // 设置确认页面
                .authorizationEndpoint(authorizationEndpoint -> authorizationEndpoint.consentPage("/oauth2/consent"))
                .oidc(Customizer.withDefaults());
        RequestMatcher endpointsMatcher = authorizationServerConfigurer
                .getEndpointsMatcher();

        http
                .securityMatcher(endpointsMatcher)
                .authorizeHttpRequests((authorize) ->
                        authorize.anyRequest().authenticated()
                )
                .csrf((csrf) -> csrf.ignoringRequestMatchers(endpointsMatcher))
                .with(authorizationServerConfigurer, Customizer.withDefaults())
        ;

        /**
         * 设置为数据库存储token
         *
         * @see org.springframework.security.oauth2.server.authorization.config.annotation.web.configurers.OAuth2ConfigurerUtils#getAuthorizationService(HttpSecurity)
         * @see
         *
         * 无需特殊注入
         * @Autowired
         * private JdbcOAuth2AuthorizationService jdbcOAuth2AuthorizationService;
         *
         * authorizationServerConfigurer.authorizationService(jdbcOAuth2AuthorizationService);
         *
         * 添加
         *     @Bean
         *     public JdbcOAuth2AuthorizationService jdbcOAuth2AuthorizationService(JdbcOperations jdbcOperations,
         *                                                                          RegisteredClientRepository registeredClientRepository) {
         *         return new JdbcOAuth2AuthorizationService(jdbcOperations, registeredClientRepository);
         *     }
         *     就可以从spring容器中获取到
         */

        /**
         * 官方页面配置
         */
//        OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http);
//        http.getConfigurer(OAuth2AuthorizationServerConfigurer.class)
//                .oidc(Customizer.withDefaults());    // Enable OpenID Connect 1.0
        http
                // Redirect to the login page when not authenticated from the
                // authorization endpoint
                .exceptionHandling((exceptions) -> exceptions
                        .defaultAuthenticationEntryPointFor(
                                new LoginUrlAuthenticationEntryPoint("/login"),
                                new MediaTypeRequestMatcher(MediaType.TEXT_HTML)
                        )
                )
                // Accept access tokens for User Info and/or Client Registration
                .oauth2ResourceServer((resourceServer) -> resourceServer
                        .jwt(Customizer.withDefaults()));

        return http.build();
    }

    @Bean
    @Order(2)
    public SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http)
            throws Exception {
        http
                .authorizeHttpRequests((authorize) -> authorize
//                        .anyRequest().permitAll()
                                .requestMatchers(HttpMethod.GET,
                                        "/login",
                                        "/oauth2/consent",
                                        "/bootstrap/**",
                                        "/images/**",
                                        "/js/**",
                                        "/favicon.ico",
                                        "/error"
                                )
                                .permitAll()
                )
                // Form login handles the redirect to the login page from the
                // authorization server filter chain
//                .formLogin(Customizer.withDefaults())
//                .exceptionHandling(exceptionHandling -> exceptionHandling
//                        .accessDeniedHandler(new JsonServerAccessDeniedHandler())
////                        .authenticationEntryPoint(new JsonAuthenticationEntryPoint())
//                )
                .formLogin(fm -> {
                    fm.loginPage("/login");
                })
        ;
        return http.build();
    }

}

